require 'recaptcha'

class AccountsController < ApplicationController
  include ReCaptcha::AppHelper
  
  layout 'accounts'

  def login
  	if current_user
  	  redirect_to admin_url
  	end
  	
  	@action_title = 'Login'
  	
  	if request.post?
  	  
  	  if @user = User.authenticate(params[:user_login], params[:user_password])
  	  	need_recap = params[:need_recap]
  	  	need_recap ||= true
  	  	# validate recaptcha
  	  	if need_recap == true && !validate_recap(params, @user.errors)
  	  	  return
  	    end
  	    
  		session[:user_id] = @user.id

  		flash[:notice] = "Success: loged in."
  		redirect_back_or_default admin_url
  		
  	  else
  	  	
  	  	flash[:notice] = "Invalid login or password"
  	  	@login = params[:user_login]
  	  	
  	  end
  	end
  end
  
  def welcome
  	
  end
  
  def signup
  	@what = params[:what]
  	@what ||= 'user'
  	case params[:what]
  	when 'lough'
  	  @action_title = 'Create your lough'  	  
  	  if session[:user_id].nil?
  	  	redirect_to :action => 'signup', :what => 'user'
  	  	return
  	  end  	  
  	  @user = User.find(session[:user_id])
  	  @lough = Lough.new(params[:lough])
  	  @lough.user = @user  	  
  	  if request.post?  	  	  	  	
  	  	if @lough.save
  	  	  flash[:notice] = 'Success: Your lough was created.'  	  	
  	  	  # send email
  	  	  send_confirmation(@user)  	  	
  	  	  redirect_to :controller => 'admin/options', :action => 'index'
  	  	  return
  	  	end
  	  end
  	else
  	  @user = User.new(params[:user])
  	  @action_title = 'Create your account'  	
  	  if request.post? and validate_recap(params, @user.errors)
  	  	if @user.save
  	      flash[:notice] = 'Success: Your account was created.'
  	      session[:user_id] = @user.id
  	      redirect_to :action => 'signup', :what => 'lough'
  	      return
  	    end
  	  end
  	end
  end
  
  def logout
  	unless current_user
  	  redirect_to :action => 'welcome' and return
  	end
  	
  	screen_name = current_lough.screen_name
  	session[:user_id] = nil  	
  	redirect_to index_url(:screen_name => screen_name)
  end
  
  protected
  
  def redirect_back_or_default(default_url = nil)
  	url = session[:return_to]
  	url ||= default_url
  	redirect_to url, :status => 301 and return
  end
  
  # Send a registration confirmation email to new user
  def send_confirmation(user)
  	AccountMailer.deliver_registration_confirm(user)
  end
  
end
